package com.ben.chatroom.session.dao.impl;

import com.ben.chatroom.common.util.JsonUtil;
import com.ben.chatroom.session.dao.UserCacheDAO;
import com.ben.chatroom.session.entity.SessionCache;
import com.ben.chatroom.session.entity.UserCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

/**
 * 用户缓存
 */
@Repository
public class UserCacheDAORedisImpl implements UserCacheDAO {


    private final StringRedisTemplate redisTemplate;
    private final static String REDIS_PREFIX = "UserCache:uid:";
    private static final long CACHE_LONG = 60 * 4;

    public UserCacheDAORedisImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void save(UserCache cache) {
        if (cache == null) {
            return;
        }
        String _key = REDIS_PREFIX + cache.getUserId();
        String _value = JsonUtil.pojoToJson(cache);
        redisTemplate.opsForValue().set(_key, _value, CACHE_LONG);
    }

    @Override
    public UserCache get(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return null;
        }

        String _val = redisTemplate.opsForValue().get(REDIS_PREFIX + userId);
        if (!StringUtils.isEmpty(_val)) {
            return JsonUtil.jsobToPojo(_val, UserCache.class);
        }

        return null;
    }

    @Override
    public void addSession(String userId, SessionCache session) {
        if (StringUtils.isEmpty(userId) || session == null) {
            return;
        }
        UserCache userCache = get(userId);
        if (null != userCache) {
            userCache.addSession(session);
        }

    }

    @Override
    public void removeSession(String userId, String sessionId) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(sessionId)) {
            return;
        }
        UserCache userCache = get(userId);
        if (null != userCache) {
            userCache.removeSession(sessionId);
        }
    }
}
